package bootstrap

import (
	"fmt"
	"github.com/astaxie/beego"
	"github.com/spf13/viper"
	"os"
	"os/signal"
	"syscall"
	"take-a-break/component/config"
	"take-a-break/component/mysql"
	"take-a-break/component/redis"
	"take-a-break/exception"
	"take-a-break/exception/recover_func"
	"time"
	"xorm.io/xorm/names"
)

func Init(args ...string) {
	configPath := "conf/app.yml"
	if len(args) > 0 {
		configPath = args[0]
	}
	//初始化配置文件
	config.FilePath = configPath
	config.Init()

	// 执行模式
	exception.RunMode = config.GetString("app.http.mode")

	// mysql model for golint
	mysql.SetColumnMapper(names.GonicMapper{})

	//初始化MySQL数据库
	if config.IsSet("mysql") {
		mysql.InitMySQL()
	}

	InitRedis()
}

func ApiInit() {
	Init()
	//配置端口号
	beego.BConfig.Listen.HTTPPort = config.GetInt("app.http.port")
	//配置运行模式
	beego.BConfig.CopyRequestBody = config.GetBool("app.http.copyRequestBody")
	// 重置beego的recover方法
	beego.BConfig.RecoverPanic = true
	beego.BConfig.RecoverFunc = recover_func.RequestRecoverPanic
	beego.BConfig.RunMode = exception.RunMode

	beego.BConfig.WebConfig.AutoRender = false
	beego.BConfig.Log.AccessLogs = false
	beego.BConfig.Log.EnableStaticLogs = false
	beego.BConfig.Listen.Graceful = false

}

// Run 启用webserver
func Run() {
	// 启动server
	go beego.Run()
	c := make(chan os.Signal, 1)
	// signal.Notify(c, syscall.SIGTERM)
	signal.Notify(c, os.Interrupt, os.Kill, syscall.SIGUSR1, syscall.SIGUSR2, syscall.SIGTERM)
	s := <-c
	fmt.Println("stopping...Got signal:", s, time.Now().String())
	if exception.RunMode != exception.DEV {
		time.Sleep(30 * time.Second)
	}
}

func InitRedis() {
	host := config.GetString("redis.default.host") + ":" + viper.GetString("redis.default.port")
	db := config.GetInt("redis.default.db")
	auth := config.GetString("redis.default.auth")
	idle := config.GetInt("redis.default.pool.idle")
	redisOpt := redis.Options{
		MaxIdle:     idle,
		MaxActive:   10,
		Host:        host,
		PassWd:      auth,
		DB:          db,
		IdleTimeout: 180,
	}
	redis.InitRedis("default", redisOpt)
}
